/**
 * 权限工具
 * @author luguoxiang
 * @date 2021-09-07
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
import { useRoute } from 'vue-router';
import { useAccountStore } from '@/store';
import { permitToReg } from '@/soar';

/**
 * 使用权限验证器
 * @param parentPermit 父权限码，非必填，自动读取当前路由权限码
 */
export function useAuth(parentPermit = `${useRoute().meta?.permit}/`) {
  const { permits, roles, user, superAdministrator } = useAccountStore();
  const regs = permits.map(permitToReg);

  /**
   * 是否有某个权限
   * @param permit
   */
  function hasPermit(permit: string) {
    permit = /^[a-zA-Z0-9].*$/.test(permit) ? `${parentPermit}${permit}` : permit;
    for (const reg of regs) {
      if (reg.test(permit)) {
        return true;
      }
    }
    return false;
  }

  /**
   * 是否有某一权限
   * @param permits
   */
  function anyPermit(...permits: string[]) {
    for (let permit of permits) {
      permit = /^[a-zA-Z0-9].*$/.test(permit) ? `${parentPermit}${permit}` : permit;
      for (const reg of regs) {
        if (reg.test(permit)) {
          return true;
        }
      }
    }
    return false;
  }

  /**
   * 是否是某个角色
   * @param role
   */
  function hasRole(role: string) {
    return roles.includes(role);
  }

  /**
   * 是否有某一角色
   * @param roles
   */
  function anyRole(...roles: string[]) {
    for (const role of roles) {
      if (roles.includes(role)) {
        return true;
      }
    }
    return false;
  }

  function hasUserType(userType: any) {
    return user.userType === userType;
  }

  function anyUserType(...userTypes: any[]) {
    for (const userType of userTypes) {
      if (user.userType === userType) {
        return true;
      }
    }
    return false;
  }

  function isSuperAdministrator() {
    return superAdministrator;
  }

  return {
    /**
     * 是否有权限
     */
    has: hasPermit,
    hasPermit,
    anyPermit,
    hasRole,
    anyRole,
    hasUserType,
    anyUserType,
    isSuperAdministrator,
  };
}
